package com.baoyang.config;

import com.baoyang.tool.api.R;
import com.baoyang.tool.api.ResultCode;
import com.baoyang.tool.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 对于登录和注册接口，直接放行，不进行token验证
        String requestURI = request.getRequestURI();
        if ("/baoyang/user/login".equals(requestURI) || "/baoyang/user/register".equals(requestURI) || "/baoyang/user/registerSwitch".equals(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("Authorization");

        // 如果没有token，继续过滤器链（让Spring Security处理未认证的请求）
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 验证token是否有效且未过期
        if (!jwtUtils.validateToken(token) || jwtUtils.isTokenExpired(token)) {
            // token无效或过期，返回403错误
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json;charset=UTF-8");

            R<?> errorResponse = R.fail(ResultCode.REQ_REJECT, "登录过期");
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(errorResponse);

            response.getWriter().write(jsonResponse);
            return;
        }

        // token有效，刷新token在Redis中的过期时间
        jwtUtils.refreshTokenExpiration(token);

        // 设置认证信息
        String userName = jwtUtils.getPhoneFromToken(token);
        Long userId = jwtUtils.getUserIdFromToken(token);

        // 把 userId 作为 principal，这样 SecurityUtils 就能直接获取
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userId, null,
                Collections.emptyList());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 如果还需要 phone，可以放到 request attribute 里
        request.setAttribute("userName", userName);

        filterChain.doFilter(request, response);
    }
}